package com.zzh.takeoutapp.view;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.model.HomeBean;
import com.zzh.takeoutapp.utils.DensityUtil;
import com.zzh.takeoutapp.utils.ImageManager;
import com.zzh.takeoutapp.viewpager.ScaleInTransformer;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class HeaderBannerView extends AbsHeaderView<List<HomeBean.DataBean.BannerBean>> {

    @Bind(R.id.vp_banner)
    ViewPager vpBanner;
    @Bind(R.id.ll_index_container)
    LinearLayout llIndexContainer;
    @Bind(R.id.rl_banner)
    RelativeLayout rlBanner;
    private static final int BANNER_TYPE = 0;
    private static final int BANNER_TIME = 5000; // ms
    private List<ImageView> ivList;
    private int bannerHeight;
    private int bannerCount;
    private Context mContext;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == BANNER_TYPE) {
                next();
                enqueueBannerLoopMessage();
            }
        }
    };

    public HeaderBannerView(Activity context) {
        super(context);
        this.mContext = context;
        ivList = new ArrayList<>();
        bannerHeight = DensityUtil.getWindowWidth(context) * 9 / 16;
    }

    @Override
    public View getView(List<HomeBean.DataBean.BannerBean> list) {
        View listView = mInflate.inflate(R.layout.header_banner_layout, null);
        ButterKnife.bind(this, listView);
        dealWithTheView(list);
        return listView;
    }

    private void dealWithTheView(List<HomeBean.DataBean.BannerBean> list) {
        ivList.clear();
        bannerCount = list.size();
        if (bannerCount == 2) {
            list.addAll(list);
        }
        RelativeLayout.LayoutParams layoutParams =
                new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.height = bannerHeight;
        rlBanner.setLayoutParams(layoutParams);
        createImageViews(list);
        HeaderBannerAdapter adapter = new HeaderBannerAdapter(ivList, mContext);
        vpBanner.setAdapter(adapter);
        //vpBanner.setPageTransformer(true, new ScaleInTransformer());
        if (vpBanner != null && ivList.size() != 0) {
            enqueueBannerLoopMessage();
        }
        addIndicatorImageViews();
        setViewPagerChangeListener();
        controlViewPagerSpeed(vpBanner, 200);
    }

    // 创建要显示的ImageView
    private void createImageViews(List<HomeBean.DataBean.BannerBean> list) {
        for (int i = 0; i < list.size(); i++) {
            ImageView imageView = new ImageView(mActivity);
            AbsListView.LayoutParams params = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            imageView.setLayoutParams(params);
            ImageManager.loadUrlImage(mActivity, list.get(i).getThumb(), imageView);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            ivList.add(imageView);
        }
    }

    // 添加指示图标
    private void addIndicatorImageViews() {
        llIndexContainer.removeAllViews();
        if (bannerCount < 2) return;
        for (int i = 0; i < bannerCount; i++) {
            ImageView iv = new ImageView(mActivity);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DensityUtil.dip2px(mActivity, 5), DensityUtil.dip2px(mActivity, 5));
            lp.leftMargin = DensityUtil.dip2px(mActivity, (i == 0) ? 0 : 7);
            iv.setLayoutParams(lp);
            iv.setBackgroundResource(R.drawable.xml_round_orange_grey_sel);
            iv.setEnabled(i == 0);
            llIndexContainer.addView(iv);
        }
    }

    // 为ViewPager设置监听器
    private void setViewPagerChangeListener() {
        vpBanner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                if (ivList == null || ivList.size() == 0) return;
                int newPosition = position % bannerCount;
                for (int i = 0; i < bannerCount; i++) {
                    llIndexContainer.getChildAt(i).setEnabled(i == newPosition);
                }
            }

            @Override
            public void onPageScrolled(int position, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    // 添加Banner循环消息到队列
    public void enqueueBannerLoopMessage() {
        if (ivList == null || ivList.size() <= 1) return;
        {
            mHandler.sendEmptyMessageDelayed(BANNER_TYPE, BANNER_TIME);
        }

    }

    //选择下一个卡片
    public void next() {
        vpBanner.setCurrentItem(vpBanner.getCurrentItem() + 1);
    }

    // 移除Banner循环的消息
    public void removeBannerLoopMessage() {
        if (mHandler.hasMessages(BANNER_TYPE)) {
            mHandler.removeMessages(BANNER_TYPE);
        }
    }

    // 反射设置ViewPager的轮播速度
    private void controlViewPagerSpeed(ViewPager viewPager, int speedTimeMillis) {
        try {
            Field field = ViewPager.class.getDeclaredField("mScroller");
            field.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(mActivity, new AccelerateDecelerateInterpolator());
            scroller.setDuration(speedTimeMillis);
            field.set(viewPager, scroller);
        } catch (Exception e) {
        }
    }

    public class HeaderBannerAdapter extends PagerAdapter {

        private List<ImageView> ivList; // ImageView的集合
        private int count; // 广告的数量
        private LayoutInflater inflater;
        private Context mContext;

        public HeaderBannerAdapter(List<ImageView> ivList, Context context) {
            super();
            this.ivList = ivList;
            this.mContext = context;
            this.inflater = LayoutInflater.from(mContext);
            if (ivList != null) {
                count = ivList.size();
            }
        }


        @Override
        public int getCount() {
            if (ivList == null) return 0;
            return Integer.MAX_VALUE;
        }


        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = ivList.get(position % ivList.size());
            ViewParent vp = view.getParent();
            if (vp != null) {
                ViewGroup parent = (ViewGroup) vp;
                parent.removeView(view);
            }
            container.addView(view);
            return view;
        }
    }

}
